<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('Document')" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
    <style>
        #document-list .list-group-item.active {
            background-color: #337ab7;
            color: #fff;
            border-color: #337ab7;
        }
    </style>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <div class="row">
        <!-- 左侧文档列表 -->
        <div class="col-sm-4" style="border-right: 1px solid #ddd;">
            <div class="list-group" id="document-list">
                <th:block th:each="doc : ${documents}">
                    <a href="javascript:;" class="list-group-item"
                       th:data-docId="${doc.docId}"
                       th:data-title="${doc.docTitle}"
                       th:data-description="${doc.docDescription}"
                       th:data-link="${doc.docLink}"
                       th:data-fileIds="${doc.docFileIds}"
                       th:text="${doc.docTitle}">
                    </a>
                </th:block>
            </div>
        </div>

        <!-- 右侧文档详情 -->
        <div class="col-sm-8">
            <input type="hidden" id="docFileIds"/>
            <div id="document-detail" style="padding-left: 20px;">
                <h4>
                    文档详情
                    <shiro:hasPermission name="system:request:document">
                        <button id="edit-btn" class="btn btn-sm btn-primary float-right">编辑</button>
                    </shiro:hasPermission>
                </h4>
                <p><strong>文档标题：</strong>
                    <span id="doc-title-view">（请选择左侧文档）</span>
                    <input type="text" id="doc-title-edit" class="form-control input-sm" style="display:none;" />
                </p>
                <p><strong>描述：</strong>
                    <span id="doc-description-view">-</span>
                    <textarea id="doc-description-edit" class="form-control input-sm" style="display:none;" rows="3"></textarea>
                </p>
                <p><strong>Link：</strong>
                    <a id="doc-link-view" href="#" target="_blank">-</a>
                    <input type="text" id="doc-link-edit" class="form-control input-sm" style="display:none;" />
                </p>
                <p><strong>附件：</strong></p>
                <div id="doc-files"><span>-</span></div>

                <shiro:hasPermission name="system:request:document">
                    <div id="upload-area" style="display:none; margin-top:10px;">
                        <div class="file-loading">
                            <input id="uploadFile" name="docFile" type="file">
                        </div>
                    </div>
                    <button id="save-btn" class="btn btn-success btn-sm" style="display:none; margin-top: 10px;">保存</button>
                </shiro:hasPermission>
            </div>
        </div>
    </div>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: bootstrap-fileinput-js" />

<script th:inline="javascript">
    var prefix = ctx + "system/request2";
    var ds = [[${documents}]];
    let currentDoc = null;

    let uploadedFileMap = {};

    $(document).ready(function () {
        const $listGroup = $('#document-list');

        $listGroup.on('click', '.list-group-item', function () {
            $('#document-list .list-group-item').removeClass('active');
            $(this).addClass('active');

            const docId = $(this).data('docid');
            const doc = ds.find(d => d.docId === docId);
            currentDoc = doc;

            $('#doc-title-view').text(doc.docTitle || '-');
            $('#doc-title-edit').val(doc.docTitle || '');

            $('#doc-description-view').text(doc.docDescription || '-');
            $('#doc-description-edit').val(doc.docDescription || '');

            $('#doc-link-view').text(doc.docLink || '-').attr('href', doc.docLink || '#');
            $('#doc-link-edit').val(doc.docLink || '');

            showFiles(doc.files || []);
            updateFileIdHiddenInput();
            exitEditMode();
        });

        function showFiles(files) {
            const $container = $('#doc-files').empty();
            if (files.length > 0) {
                files.forEach((file, index) => {
                    const fileEl = $(`
                        <p>
                            <a href="${prefix}/downloadFile/${file.fileId}" target="_blank">${file.fileName}</a>
                            <button class="btn btn-xs btn-danger delete-file" data-index="${index}" style="margin-left:10px; display:none;">删除</button>
                        </p>`);
                    $container.append(fileEl);
                });
            } else {
                $container.html('<p>无附件</p>');
            }
        }

        // 编辑按钮切换模式
        $('#edit-btn').on('click', function () {
            $('#doc-title-view, #doc-description-view, #doc-link-view').hide();
            $('#doc-title-edit, #doc-description-edit, #doc-link-edit').show();
            $('#upload-area, #save-btn').show();
            $('#doc-files .delete-file').show();

        });

        // 初始化bootstrap-fileinput
        $("#uploadFile").fileinput({
            uploadUrl: prefix + '/uploadDoc/upload', //上传的地址
            uploadAsync: true, //是否异步上传
            showCaption: false,  //input框是否显示
            showUpload: false,   //上传按钮是否显示
            showPreview: false, //预览区域
            showClose: false, //关闭按钮
            showRemove: false, //移除按钮
            autoUpload: true, //选择文件后是否自动上传
            dropZoneTitle: '拖拽文件到这里上传',
            maxFileCount: 5,
            maxFileSize: 500 * 1024   //单位kb，文件最大500M
        }).on('filebatchselected', function(event, files) {
            // 自动上传
            $(this).fileinput("upload");
        }).on('fileuploaded', function (event, data, previewId, index) {
            // 上传成功后处理
            const fileId = data.response.fileId;
            const fileName = data.response.fileName;

            if (fileId && fileName) {
                // 将新上传的文件添加到 uploadedFileMap
                uploadedFileMap[previewId] = fileId;

                // 同步添加到 currentDoc.files
                if (!currentDoc.files) {
                    currentDoc.files = [];
                }
                currentDoc.files.push({
                    fileId: fileId,
                    fileName: fileName
                });

                // 刷新附件展示区域
                showFiles(currentDoc.files);
                $('#doc-files .delete-file').show();

                // 更新隐藏域
                updateFileIdHiddenInput();
            }
        })

        // 更新隐藏域
        function updateFileIdHiddenInput() {
            const fileIds = [];

            // 添加已存在的附件
            if (currentDoc && currentDoc.files) {
                currentDoc.files.forEach(file => {
                    if (file.fileId) {
                        fileIds.push(file.fileId);
                    }
                });
            }

            $('#docFileIds').val(fileIds.join(','));
        }

        // 保存
        $('#save-btn').on('click', function () {
            if (!currentDoc) return;

            const newTitle = $('#doc-title-edit').val();
            const newDesc = $('#doc-description-edit').val();
            const newLink = $('#doc-link-edit').val();
            const newFileIds = $('#docFileIds').val();

            currentDoc.docTitle = newTitle;
            currentDoc.docDescription = newDesc;
            currentDoc.docLink = newLink;
            currentDoc.docFileIds = newFileIds;

            // 更新左侧列表显示
            $(`#document-list .list-group-item[data-docid="${currentDoc.docId}"]`)
                .text(newTitle)
                .data('title', newTitle)
                .data('description', newDesc)
                .data('link', newLink);

            // 更新视图
            $('#doc-title-view').text(newTitle);
            $('#doc-description-view').text(newDesc);
            $('#doc-link-view').text(newLink).attr('href', newLink);

            exitEditMode();
            updateFileIdHiddenInput();
            // AJAX 提交
            $.ajax({
                type: 'POST',
                url: prefix + '/updateDocument',
                data: {
                    docId: currentDoc.docId,
                    docTitle: newTitle,
                    docDescription: newDesc,
                    docLink: newLink,
                    docFileIds: newFileIds
                },
                success: function (response) {
                    if (response.code === 0) {
                        layer.msg('保存成功', {icon: 1});
                    } else {
                        layer.msg('保存失败: ' + response.msg, {icon: 2});
                    }
                },
                error: function () {
                    layer.msg('保存失败，请稍后重试', {icon: 2});
                }
            });
        });

        // 删除附件
        $('#doc-files').on('click', '.delete-file', function () {
            const index = $(this).data('index');
            if (currentDoc && currentDoc.files) {
                currentDoc.files.splice(index, 1);
                showFiles(currentDoc.files);
                $('#doc-files .delete-file').show(); // 保持可见
                updateFileIdHiddenInput();
            }
        });

        function exitEditMode() {
            $('#doc-title-view, #doc-description-view, #doc-link-view').show();
            $('#doc-title-edit, #doc-description-edit, #doc-link-edit').hide();
            $('#upload-area, #save-btn').hide();
            $('#doc-files .delete-file').hide();
        }

        if (ds.length > 0) {
            $('#document-list .list-group-item:first').trigger('click');
        } else {
            $('#doc-title-view').text('无文档');
            $('#doc-description-view').text('-');
            $('#doc-link-view').text('-').attr('href', '#');
            $('#doc-files').html('<p>无附件</p>');
        }
    });
</script>
</body>
</html>
